package com.sharemarking.application.common.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.sharemarking.application.common.BaseSpecification;
import com.sharemarking.application.common.entity.Employee;
import com.sharemarking.application.common.repository.DepartmentRepo;
import com.sharemarking.application.common.repository.EmployeeRepo;

@Controller
@RequestMapping("employee")
public class EmployeeController {
	

	@Autowired
	EmployeeRepo er;
	
	@Autowired
	DepartmentRepo dr;
	

	@RequestMapping("getAllEmployee")
	@ResponseBody
	public List<Employee> getAllEmployee(){
		List<Employee> list=null;
		list=(List<Employee>) er.findAll();
		return list;
	}
	
	

	/**
	 * 数据列表页
	 * 
	 * @param employee
	 * @param page
	 * @param size
	 * @param model
	 */
	@GetMapping(value = "index")
	@PreAuthorize("hasPermission('sys:employee',1)")
	public void index(Employee e, Integer page, Integer size, Model model) {
		if (page == null) {
			page = 0;
		} else {
			page -= 1;
		}
		if (size == null) {
			size = 5;
		}
		// 按照id降序
		Sort sort = new Sort(Direction.DESC, "id");
		PageRequest req = new PageRequest(page, size, sort);
		Page<Employee> p = er.findAll(new BaseSpecification<Employee>(e), req);
		String pro="http://113.71.26.27:8080/tpl/public/uploadImage/peopleLogo/";
		model.addAttribute("pro", pro);
		model.addAttribute("page", p);
		model.addAttribute("search", e);

	}
	
	

	/**
	 * 获取实体接口
	 * 
	 * @param obj
	 * @param model
	 * @return
	 */
	@GetMapping(value = "{id}")
	@PreAuthorize("hasPermission('sys:employee',1)")
	public String get(Employee obj, Model model) {
		if (obj.getId() != 0)
			obj = er.findOne(obj.getId());
		String pro="http://113.71.26.27:8080/tpl/public/uploadImage/peopleLogo/";
		model.addAttribute("pro", pro);
		model.addAttribute("obj", obj);

		return "employee/form";
	}

	/**
	 *员工新增和编辑
	 * 
	 * @param target
	 * @param model
	 * @return
	 * @throws IOException
	 * @throws NoSuchAlgorithmException 
	 */
	@PostMapping(value = "{id}")
	@Transactional
	@PreAuthorize("hasPermission('sys:employee',#target.id==0?8:4)")
	public String post(Employee target, Model model, @RequestParam("PICN") MultipartFile PICN, HttpServletRequest request)
			throws IOException, NoSuchAlgorithmException {
	

		if (!PICN.isEmpty()) {
			// 文件上传
//			String PICName = null;
			
			MultipartFile file = PICN;
//			PICName = file.getOriginalFilename();
			// 把要上传的图片转换成流
			InputStream isRef = file.getInputStream();
 
			// 获取classes下的路径
//			String path = this.getClass().getClassLoader().getResource("").getPath() + "public/uploadImage/peopleLogo/";
			String targetDir1 = this.getClass().getClassLoader().getResource("").getPath() + "public/uploadImage/peopleLogo";
			File file1 = new File(targetDir1);
			file1.mkdirs();
			
			// 图片命名为loginName+Data+8位随机数.png
			Date now = new Date();
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");// 可以方便地修改日期格式

			String Date = dateFormat.format(now);
			StringBuilder str = new StringBuilder();// 定义变长字符串

			// 随机生成数字，并添加到字符串
			Random random = new Random();
			for (int i = 0; i < 8; i++) {
				str.append(random.nextInt(10));
			}

//			String path2 = path + Date + str.toString() + ".png";
			String path3 = Date + str.toString() + ".png";
			
			File targetFile = new File(targetDir1, path3);
			// 通过输出流将图片写入到相应的地方
			FileOutputStream fosRef = new FileOutputStream(targetFile);
			IOUtils.copy(isRef, fosRef);
			
			// 添加
			if (target.getId() == 0) {

				// 将接收的文件保存到指定文件中
				target.setImgUrl(path3);
				// 保存图片路径
				PICN.transferTo(targetFile);
				//密码加密
				MessageDigest md = MessageDigest.getInstance("MD5");
			    md.update(target.getPassword().getBytes());
				
				String pwd = new BigInteger(1,md.digest()).toString(16);
				target.setPassword(pwd);
				
				er.save(target);
				return "redirect:index";
			} else {
				// 编辑
				Employee employee = er.findOne(target.getId());
				if (employee == null)
					return null;

				// 将接收的文件保存到指定文件中
				PICN.transferTo(targetFile);
				employee.setLoginName(target.getLoginName());
				employee.setPhone(target.getPhone());
				employee.setEmail(target.getEmail());
				employee.setAge(target.getAge());
				employee.setSex(target.getSex());
				employee.setJob(target.getJob());
				employee.setAddress(target.getAddress());
				employee.setImgUrl(path3);
			}
		}else{
			// 当PICN为空时 编辑
			Employee employee = er.findOne(target.getId());
			if (employee == null)
				return null;
			
			employee.setLoginName(target.getLoginName());
			employee.setPhone(target.getPhone());
			employee.setEmail(target.getEmail());
			employee.setAge(target.getAge());
			employee.setSex(target.getSex());
			employee.setJob(target.getJob());
			employee.setAddress(target.getAddress());
			
			return "redirect:index";
		
		}
		return "redirect:index";
	}

	/**
	 * 删除员工
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping(value = "{id}/delete")
	@Transactional
	public String delete(@PathVariable("id") Integer id) {
		er.findOne(id).setDelFlag(true);
		return "redirect:../index";
	}
	
	//ajax验证员工的唯一性
	@PostMapping(value="checkName")
	@ResponseBody
	public String findByName(String param){
		return er.findByName(param)!=null?"该员工已存在了":"y";
	}
	 

}
